package main

import (
	"database/sql"
	"flag"
	"fmt"
	"log"
	"os"

	"gitee.com/liumou_site/database-initialized/pkg/dbutils"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	var (
		dbUser      = flag.String("user", "", "Database username")
		dbPassword  = flag.String("password", "", "Database password")
		dbHost      = flag.String("host", "", "Database host (without port)")
		port        = flag.Int("port", 3306, "Database port")
		dbName      = flag.String("dbname", "", "Database name")
		sqlFile     = flag.String("file", "", "SQL file path")
		forceImport = flag.Bool("force", false, "Force import even if tables exist")
	)

	flag.Parse()
	// 在flag.Parse()后添加参数校验

	if *dbUser == "" || *dbPassword == "" || *dbHost == "" || *dbName == "" || *sqlFile == "" {
		fmt.Println("All parameters are required")
		flag.PrintDefaults()
		os.Exit(1)
	}

	// 建立数据库连接
	db, err := dbutils.ConnectDB(*dbUser, *dbPassword, *dbHost, *port, *dbName)
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
		return
	}
	defer func(db *sql.DB) {
		err = db.Close()
		if err != nil {
			log.Fatal("Failed to close database:", err)
		}
	}(db)

	// 在读取SQL文件后添加表存在检查
	if !*forceImport {
		exists, err := dbutils.CheckTablesExist(db, *dbName)
		if err != nil {
			log.Fatal("Table check failed:", err)
		}
		if exists {
			fmt.Println("The data table already exists. To overwrite it, please use - force")
			return
		} else {
			fmt.Println("Target table does not exist, import begins")
		}
	}
	err = dbutils.ExecSqlScript(*sqlFile, db)
	if err != nil {
		log.Fatal("Failed to execute SQL script:", err)
		return
	}
	fmt.Println("SQL file imported successfully!")
}
